package sandbox;

import helpers.d;
import soenudp.Command;
import soenudp.UDPHelper;
import soenudp.UDPMessage;

public class FakeMTLGroup {
  
  final static int    GMS_PORT = 20000; 
  final static String MTL_MULTICAST_ADR   = "235.255.0.1";
  final static int    MTL_MULTICAST_PORT  = 9200;
  
  /* To join  different groups (ex: TOR, MTL) change MULTICAST_ADR or MULTI_CAST_PORT. */
  static String nodeID;
 
  public static void main(String[] args) throws InterruptedException
  { 
    Runnable testRun = new Runnable()
    { 
      @SuppressWarnings("unused")
      public void run()
      {     
        try {
            UDPHelper groupHelper   = new UDPHelper();
            UDPHelper socketHelper  = new UDPHelper();
            String _nodeID = new String(nodeID);
            
            // The 'false' value is to receive message from the broadcast.
            groupHelper.joinGroup(MTL_MULTICAST_ADR, MTL_MULTICAST_PORT, false, "Group Member " + _nodeID);
            
            socketHelper.startUnicastServer(_nodeID, 9927);//startUnicastClient("Group Member " + _nodeID);

            Thread unicastCallbacks = new Unicast2Unicast(socketHelper,groupHelper,Thread.currentThread());
            unicastCallbacks.start();
            
            System.out.println("Started Group Member " + _nodeID);
            UDPMessage request;

            // Will wait in while() if no new messages
            while ( (request = groupHelper.getMsgFromGroup()) != null )
            {
              int       fromPort  = request.recv_from_port;
              long      transacid = request.transac;
              String    fromIP    = request.recv_from_ip;
              String    optioText = request.op_text; //in case you need more...
              Command   command   = request.command;
            
              switch(command)
              {
                case BPING:
                  
                  UDPMessage response = new UDPMessage();
                  response.command = Command.PONG;     
                  response.op_text = _nodeID;
                  socketHelper.sendToNode(fromIP, GMS_PORT, response); //Reply back.
                  
                  break;
                  
                default:
                  System.out.println("Received " + command +  " From IP: " + fromIP + 
                    " PORT: " + fromPort + " Transaction id: " + transacid);
                  break;
              }
            }
        } 
        catch (soenudp.UDPException e)
        {  
          e.printStackTrace();
        }
      }
    };
    
    Thread receiverThread = new Thread(testRun);
    for (int i = 2; i < 3; i++)
    { 
      nodeID = "MTL00" + i;
      receiverThread.start();  
      d.sleep(500);
    }
    
    while(receiverThread.isAlive()) d.sleep(777);
    d.listAllThreads();
  }
}
